<template>
	<el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="search()">
			<el-form-item label="关键词" prop="keyword">
				<el-input v-model="state.keyword" placeholder="请输入" clearable>
					<template #prepend>
						<el-select v-model="state.keyType" placeholder="请选择" style="width: 100px; min-width: 100px">
							<el-option label="项目名称" value="1" />
							<el-option label="项目编号" value="2" />
							<el-option label="负责人" value="3" />
							<el-option label="联系人" value="4" />
							<el-option label="承担单位" value="5" />
						</el-select>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="申报年份" prop="yearrange">
				<el-date-picker
					v-model="state.yearrange"
					type="yearrange"
					format="YYYY"
					value-format="YYYY"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					style="width: 100%"
				/>
			</el-form-item>
			<el-form-item label="过程阶段" prop="processStage">
				<el-select v-model="state.queryForm.processStage" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in processStage" :key="item.value" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="进度状态" prop="processStatus">
				<el-select v-model="state.queryForm.processStatus" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in scheduleStatus" :key="item.value" :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="search()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset()">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>
	<el-card>
		<el-form :inline="true" style="text-align: right" class="anniu">
			<el-form-item label="模板下载">
				<el-select v-model="tempId" placeholder="请选择" style="width: 100%" clearable>
					<el-option v-for="item in tempList" :key="item.id" :label="item.fileName" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="downLoadTemplate()">下载</el-button>
			</el-form-item>
		</el-form>
		<el-table v-loading="state.dataListLoading" :data="dataList" stripe :row-class-name="tableRowClassName" border>
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
			<el-table-column prop="projectNumber" label="项目编号" header-align="center" align="center" width="140" resizable sortable></el-table-column>
			<el-table-column
				prop="researchName"
				label="项目名称"
				header-align="center"
				align="center"
				width="200"
				show-overflow-tooltip
				resizable
				sortable
			></el-table-column>
			<el-table-column prop="contacts" label="联系人" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column
				prop="contactsTel"
				label="联系人电话(手机)"
				header-align="center"
				align="center"
				width="120"
				resizable
				sortable
			></el-table-column>
			<el-table-column prop="principal" label="负责人" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column prop="principalTel" label="负责人电话" header-align="center" align="center" width="120" resizable sortable />
			<el-table-column prop="responsibleEnt" label="承担单位" header-align="center" align="center" width="120" resizable sortable />
			<el-table-column prop="projectFunding" label="课题总经费(万元)" header-align="center" align="center" width="150" resizable sortable />
			<el-table-column prop="applyYear" label="申报年份" header-align="center" align="center" resizable sortable width="120" />
			<el-table-column prop="projectManager" label="项目管理员" header-align="center" align="center" width="160" resizable sortable />
			<el-table-column prop="processStage" label="过程阶段" header-align="center" align="center" width="120" resizable sortable>
				<template #default="scope">
					<span>{{ processStage.filter(item => item.value == scope.row.processStage)[0].label }}</span>
				</template>
			</el-table-column>
			<el-table-column label="已归档" header-align="center" align="center" width="120" resizable sortable>
				<template #default="scope">
					<el-icon v-if="scope.row.processStage == '7'" color="#1491FF" size="26"><SuccessFilled /></el-icon>
				</template>
			</el-table-column>
			<el-table-column label="成果发布" header-align="center" align="center" width="120" resizable sortable>
				<template #default="scope">
					<el-icon
						v-if="scope.row.achievementReleaseStatus == '0'"
						color="#1491FF"
						size="26"
						style="cursor: pointer"
						@click="handleViewResult(scope.row)"
						><SuccessFilled
					/></el-icon>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="120">
				<template #default="scope">
					<el-icon
						v-if="Number(scope.row.processStage) < 6"
						v-auth="'M005_2_U'"
						:size="16"
						color="#1491FF"
						title="编辑"
						style="cursor: pointer; margin: 0 6px"
						@click="handleEdit(scope.row)"
					>
						<Edit />
					</el-icon>
					<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="handleView(scope.row)">
						<View />
					</el-icon>
					<el-icon
						v-if="scope.row.processStage == '6' && scope.row.processStatus == '1'"
						v-auth="'M005_2_File'"
						:size="16"
						color="#1491FF"
						title="待归档"
						style="cursor: pointer; margin: 0 6px"
						@click="handleFile(scope.row)"
					>
						<FolderOpened />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
	</el-card>
	<addDialog v-model="showAddDialog" :edit-id="editId" :is-view="isView" :is-audit="false" @submit-success="addSuccess"> </addDialog>
	<fileDialog v-model="showFileDialog" :edit-id="editId" :is-view="isView" :is-audit="false" @submit-success="addSuccess"> </fileDialog>
</template>
<script setup lang="ts">
import { delDeclare } from '@/api/declare'
import { getList, getTemplate } from '@/api/Prospect-project/process-declare'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import addDialog from '../components/addDialog.vue'
import fileDialog from '../components/fileDialog.vue'
const route = useRoute()
const pendingStatus = route.query.pendingStatus

const userStore = useUserStore()

const processStage = [
	{
		label: '开题',
		value: '3'
	},
	{
		label: '中期',
		value: '4'
	},
	{
		label: '结题',
		value: '5'
	},
	{
		label: '等待归档',
		value: '6'
	},
	{
		label: '已归档',
		value: '7'
	}
]
const scheduleStatus = [
	{
		label: '正常',
		value: '1'
	},
	{
		label: '滞后',
		value: '2'
	}
]
const processStatus = [
	{
		label: '未提交',
		value: '0'
	},
	{
		label: '未处理',
		value: '1'
	},
	{
		label: '已处理',
		value: '2'
	}
]

const state = reactive({
	queryForm: {
		researchName: '',
		projectNumber: '',
		principal: '',
		contacts: '',
		processStage: '',
		projectManager: '',
		scheduleStatus: '',
		processStatus: '',
		approvalReview: '',
		startYear: '',
		endYear: '',
		responsibleEnt: '',
		pendingStatus: pendingStatus || ''
	},
	pageNum: 1,
	pageSize: 10,
	total: 1,
	dataListLoading: false,
	keyType: '',
	keyword: null,
	yearrange: []
})

const dataList = ref([])
const showAddDialog = ref<boolean>(false)
const editId = ref<string>('')
const isView = ref<boolean>(false)
const isAudit = ref<boolean>(false)

const showFileDialog = ref<boolean>(false)

const tempList = ref<any>([])
const tempId = ref('')

watch(
	() => showAddDialog.value,
	newVal => {
		if (newVal == false) {
			editId.value = ''
			isView.value = false
			isAudit.value = false
		}
	}
)

watch(
	() => showFileDialog.value,
	newVal => {
		if (newVal == false) {
			editId.value = ''
			isView.value = false
			isAudit.value = false
		}
	}
)

const handleViewResult = (row: any) => {
	showFileDialog.value = true
	editId.value = row.id
	isView.value = true
}

const tableRowClassName = ({ row }: { row: any }) => {
	if (row.progressColor) {
		return row.progressColor
	}
}

const getDataList = () => {
	state.queryForm.researchName = ''
	state.queryForm.projectNumber = ''
	state.queryForm.principal = ''
	state.queryForm.contacts = ''
	state.queryForm.responsibleEnt = ''
	state.queryForm.startYear = ''
	state.queryForm.endYear = ''
	switch (state.keyType) {
		case '1':
			state.queryForm.researchName = state.keyword
			break
		case '2':
			state.queryForm.projectNumber = state.keyword
			break
		case '3':
			state.queryForm.principal = state.keyword
			break
		case '4':
			state.queryForm.contacts = state.keyword
			break
		case '5':
			state.queryForm.responsibleEnt = state.keyword
			break
	}
	if (state.yearrange !== null) {
		if (state.yearrange.length > 0) {
			state.queryForm.startYear = state.yearrange[0]
			state.queryForm.endYear = state.yearrange[1]
		}
	}
	state.dataListLoading = true
	getList({
		pageIndex: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		state.dataListLoading = false
		dataList.value = res.data.list || []
		state.total = res.data.total || 0
	})
}

const search = () => {
	state.pageNum = 1
	getDataList()
}

const reset = () => {
	state.yearrange = []
	state.queryForm.researchName = ''
	state.queryForm.projectNumber = ''
	state.queryForm.principal = ''
	state.queryForm.contacts = ''
	state.queryForm.processStage = ''
	state.queryForm.projectManager = ''
	state.queryForm.scheduleStatus = ''
	state.queryForm.processStatus = ''
	state.queryForm.approvalReview = ''
	state.queryForm.startYear = ''
	state.queryForm.endYear = ''
	state.queryForm.responsibleEnt = ''
	state.queryForm.pendingStatus = ''
	state.keyword = ''
	state.keyType = ''
	state.pageNum = 1
	getDataList()
}

const handleAddNew = () => {
	showAddDialog.value = true
	editId.value = ''
	isAudit.value = true
}

const handleEdit = (row: any) => {
	editId.value = row.id
	showAddDialog.value = true
}

const handleView = (row: any) => {
	isView.value = true
	editId.value = row.id
	showAddDialog.value = true
}

const selectionChangeHandle = () => {}
const sizeChangeHandle = (e: number) => {
	state.pageSize = e
	state.pageNum = 1
	getDataList()
}
const currentChangeHandle = (e: number) => {
	state.pageNum = e
	getDataList()
}

const addSuccess = (e: any) => {
	editId.value = ''
	showAddDialog.value = false
	showFileDialog.value = false
	reset()
}

const handleFile = (row: any) => {
	showFileDialog.value = true
	editId.value = row.id
}

const handleDel = (row: any) => {
	ElMessageBox.confirm(`是否删除'${row.standardProjectName}'的申报信息,删除后无法恢复!`, '温馨提示', {
		confirmButtonText: '删除',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			delDeclare({
				id: row.id
			}).then(() => {
				getDataList()
				ElMessage.success('删除申报成功')
			})
		})
		.catch(() => {})
}

const getTempList = () => {
	getTemplate({
		templateType: '2'
	}).then(res => {
		tempList.value = res.data || []
	})
}

const downLoadTemplate = () => {
	if (tempId.value == '') {
		ElMessage.error('请先选择模板')
		return
	}
	const temp = tempList.value.find((item: any) => item.id === tempId.value)
	try {
		const param = {
			fileName: temp.fileName
		}
		const fileType = {
			pdf: 'application/pdf',
			doc: 'application/msword',
			docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
			xls: 'application/vnd.ms-excel',
			xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
		}
		axios({
			method: 'post',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/api/scientificResearchInfo/downloadByFileName',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			data: param,
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: fileType[temp.fileExtName]
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = `${temp.fileName}.${temp.fileExtName}`
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

onMounted(() => {
	getDataList()
	getTempList()
})
</script>
<style lang="scss" scoped>
.title {
	font-size: 20px;
	text-align: center;
}

.subtitle {
	font-size: 16px;
	margin: 30px 0 10px;
}

.form {
	display: flex;
	flex-wrap: wrap;

	.item {
		display: flex;
		align-items: center;
		min-width: 33.33%;

		.label {
			font-size: 14px;
			height: 30px;
			line-height: 30px;
		}

		.value {
			padding: 2px 20px 2px 5px;
			border-bottom: solid 1px #333;
			font-size: 14px;
			margin-right: 50px;
			flex: 1;
			height: 30px;
			line-height: 30px;
		}
	}
}

.form2 {
	margin-top: 20px;

	.label {
		line-height: 20px;
	}

	.value {
		border-bottom: solid 1px #333;
		font-size: 14px;
		line-height: 28px;
	}
}
</style>
